import React, { Component } from 'react'
import './css/index.css'

export default class App extends Component {
  state = {
    myText: '',
    todoList: [
      { id: 1, complete: false, todo: 'aa' },
      { id: 2, complete: false, todo: 'bb' },
      { id: 3, complete: false, todo: 'bb' },
    ],
  }
  render() {
    return (
      <>
        <div>22-10-todo-list</div>
        <div>
          <input
            type='text'
            placeholder=''
            value={this.state.myText}
            onChange={(evt) => this.setState({ myText: evt.target.value })}
          />
          <button
            type='button'
            onClick={(evt) => this.handleAdd()}
          >
            add
          </button>
        </div>
        <div>
          <ul>
            {this.state.todoList.map((item, index) => {
              return (
                <li key={item.id}>
                  <input
                    type='checkbox'
                    checked={item.complete}
                    onChange={() => this.handleChange(index)}
                  />
                  <span
                    style={{
                      textDecoration: item.complete ? 'line-through' : 'none',
                    }}
                  >
                    {item.todo}
                  </span>
                  <button
                    type='button'
                    onClick={() => this.handleDel(index)}
                  >
                    del
                  </button>
                </li>
              )
            })}
          </ul>

          {
            <div className={this.state.todoList.length !== 0 ? 'hidden' : ''}>
              暂无代办事项
            </div>
          }
        </div>
      </>
    )
  }

  handleAdd = () => {
    if (!this.state.myText) {
      return
    }
    // 复制
    let todoList = [...this.state.todoList]
    todoList.push({
      id: Math.random(),
      complete: false,
      todo: this.state.myText,
    })
    this.setState({
      todoList,
      myText: '',
    })
  }

  handleDel = (index) => {
    // 复制
    let todoList = this.state.todoList.concat()
    // 删除元素
    todoList.splice(index, 1)
    this.setState({
      todoList,
    })
  }

  handleChange = (index) => {
    // 复制
    let todoList = this.state.todoList.slice()
    todoList[index].complete = !todoList[index].complete
    this.setState({
      todoList,
    })
  }
}
